<template>
  <el-select
    filterable
    collapse-tags
    ref="selectRef"
    :multiple="multiple"
    v-model="selectValue"
    :clearable="clearable"
    collapse-tags-tooltip
    :placeholder="placeholder"
    :filter-method="handleQuerySearch"
    @visible-change="visibleChange"
    @change="handleQueryChange"
    @paste.native="pasteNativeSreach"
  >
    <el-option
      v-for="item in selectOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
    <VabElSelectLoading
      :page="page"
      :loading="loading"
      :hasMore="hasMore"
      @loadMore="handleLoadMore"
    />
  </el-select>
</template>

<script setup lang="ts">
  /**
   * @import
   */
  import _ from 'lodash'
  import { ref } from 'vue'
  import { homeProductSearchSelect } from '~/src/api/dms/home/homeCustomer'
  import { ArrayOneValue } from '~/src/utils/utils'

  /**
   * @props
   */
  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: '', // number, name, assistant_id, product_code barcode
    },
    // 买方
    customerNumber: {
      type: String,
      default: '',
    },
    // 品牌
    assistant_id: {
      type: Array,
      default: [],
    } as any,
    multiple: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
  })

  /**
   * @var
   */

  const proxy: any = getCurrentInstance()?.proxy
  const selectRef = ref()
  const page = ref(0)
  const loading = ref(false)
  const hasMore = ref(true)

  const selectValue = ref<any>()
  const sreachValue = ref<any>('')
  const selectOptions = ref<any[]>([])

  /**
   * @method
   */

  const emit = defineEmits(['LazyChange', 'pasteNative'])

  /**
   * 加载数据列表
   */
  const loadDataList = async (pasteValue = '') => {
    sreachValue.value = pasteValue ? pasteValue : sreachValue.value

    try {
      loading.value = true
      // 参数
      let data = {
        page: page.value,
        limit: 20,
        filter: {
          customer_number: props.customerNumber,
          name:
            props.type == '' ||
            props.type == 'name' ||
            props.type == 'product_code'
              ? sreachValue.value
              : '', // 物料名称
          number: props.type == 'number' ? sreachValue.value : '', // 物料编码
          barcode: props.type == 'barcode' ? sreachValue.value : '', // 条码
          assistant_id: props.assistant_id || '', // 品牌
          class_id1: '', //一级类目
          class_id2: '', //二级类目
        },
      }

      // api
      const res = await homeProductSearchSelect({ ...data })

      // 遍历获取
      const list =
        res.data.list.map((item: any) => {
          // 复合查询
          if (!props.type)
            return { value: item.number, label: `${item.number}-${item.name}` }
          if (props.type == 'name')
            return { value: item.name, label: item.name }
          if (props.type == 'number')
            return { value: item.number, label: item.number }

          if (props.type == 'product_code')
            return { value: item.number, label: item.name }

          if (props.type == 'assistant_id')
            return { value: item.assistant_id, label: item.assistant_name }

          if (props.type == 'barcode')
            return { value: item.barcode, label: item.barcode }
        }) || []

      if (page.value == 1) selectOptions.value = []

      selectOptions.value.push(...list)
      hasMore.value = selectOptions.value.length < res.data.count
    } catch (err) {
      console.error(err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 加载更多数据
   */

  const handleLoadMore = _.throttle(async (value: any) => {
    if (!props.customerNumber) {
      proxy.$Message('请选择买方，再进行操作！', 'warning')
      return
    }
    page.value = await value
    loadDataList()
  }, 500)

  /**
   * 模糊搜索
   */
  const handleQuerySearch = _.throttle((value: any) => {
    if (!props.customerNumber) return

    // 去空格 大小写
    if (props.multiple) {
      //多选 空格转回车
      sreachValue.value = value?.trim().toLowerCase().replace(/\s+/g, '\n')
    } else {
      sreachValue.value = value?.trim().toLowerCase()
    }

    page.value = 1
    // 加载数据
    loadDataList()
  }, 500)

  // 快粘贴筛选
  const pasteNativeSreach = async (e: any) => {
    // 获取黏贴值
    let clipboardData: any = e.clipboardData // IE
    if (!clipboardData) {
      //chrome
      clipboardData = e.originalEvent.clipboardData
    }
    const text = await clipboardData.getData('Text')
    const reg = /[\s;]+/
    const paste = await text.split(reg)

    await loadDataList(paste)

    emit('pasteNative', {
      options: ArrayOneValue(selectOptions.value, 'value'),
      type: props.type,
    })
  }

  /**
   * change
   */
  const handleQueryChange = (value: any) => {
    emit('LazyChange', value)
  }

  const visibleChange = (lay: boolean) => {
    selectOptions.value = []
    page.value = 1
    if (lay) loadDataList()
  }

  /**
   * @实例
   */

  watch(
    () => props.value,
    (newValue, oldValue) => {
      selectValue.value = newValue
    },
    { deep: true, immediate: true }
  )

  defineExpose({
    loadDataList,
  })
</script>

<style lang="scss" scoped></style>
